<?php
class AjaxController extends CController
{
    protected function beforeAction($action)
    {
        // check login
        if(!FacebookUtility::getUserId())
        {
            throw new CHttpException(401, 'Unauthorized');
        }

        // check ajax & post
        $request = Yii::app()->request;
        if(!$request->isAjaxRequest || !$request->isPostRequest)
        {
            throw new CHttpException(403, 'Forbidden');
        }

        return parent::beforeAction($action);
    }

    public function actionUpdateSnapshotPreference()
    {
        // params
        $request = Yii::app()->request;
        $userId = FacebookUtility::getUserId();
        $searchPurposeId = $request->getParam('searchPurposeId');
        $interestId = $request->getParam('interestId');
        $genderId = $request->getParam('genderId');
        $ageFrom = $request->getParam('ageFrom');
        $ageTo = $request->getParam('ageTo');
        $cityId = $request->getParam('cityId');
        $distance = $request->getParam('distance');

        // update search purpose
        UserUtility::updateSearchPurpose($userId, $searchPurposeId);

        // update preference
        SnapshotUtility::updatePreference($userId, $interestId, $genderId, $ageFrom, $ageTo, $cityId, $distance);

        // rebuild snapshot
        SnapshotUtility::build($userId);

        // response
        $data = array();
        $data['targets'] = SnapshotUtility::getTargets($userId, 0, CONST_SNAPSHOT_QUEUE_MAX_ITEM);
        echo json_encode($data);
    }

    public function actionPlaySnapshot()
    {
        // params
        $request = Yii::app()->request;
        $userId = FacebookUtility::getUserId();
        $isLike = $request->getParam('isLike');

        // play snapshot
        SnapshotUtility::play($userId, $isLike);

        // get next target
        $targetId = SnapshotUtility::getTarget($userId, CONST_SNAPSHOT_QUEUE_MAX_ITEM - 1);
        $target = UserUtility::getInfo($targetId);

        // response
        $data = array();
        $data['nextTarget'] = $target;
        echo json_encode($data);
    }

    public function actionSearch()
    {
        // params
        $request = Yii::app()->request;
        $userId = FacebookUtility::getUserId();
        $searchPurposeId = $request->getParam('searchPurposeId');
        $interestId = $request->getParam('interestId');
        $genderId = $request->getParam('genderId');
        $ageFrom = $request->getParam('ageFrom');
        $ageTo = $request->getParam('ageTo');
        $cityId = $request->getParam('cityId');
        $distance = $request->getParam('distance');

        // update search purpose
        UserUtility::updateSearchPurpose($userId, $searchPurposeId);

        // update preference
        SearchUtility::updatePreference($userId, $interestId, $genderId, $ageFrom, $ageTo, $cityId, $distance);

        // response
        $data = array();
        echo json_encode($data);
    }
}